package gameEngine.agents.Logger.Massages;

import exportSystem.statistics.Statistics;
import gameEngine.game.TurnBasedScoredGame;

import org.apache.log4j.Logger;
/**
 * creates a textual massage for csv logger
 * @author alon
 *
 */
public class CSVMassage implements Massage {

	String agentID;
	String lastId;
	String score;
	String lastScore;
	TurnBasedScoredGame game;
	Logger log = Logger.getLogger(this.getClass());
	
	public CSVMassage(TurnBasedScoredGame game) {
		super();
		this.game = game;
	}

	public String getAgentID() {
		return agentID;
	}

	public void setAgentID(String agentID) {
		this.agentID = agentID;
	}

	public String getScore() {
		return score;
	}

	public void setScore(String score) {
		this.score = score;
	}
	/**
	 * creates a massage at the format:
	 * turn,0,0,x,0,0,nextPlayer where x is current agents score
	 */
	public String getMassage() {

		String message;
		//first massage is the tables header
		if(game.getTurnNumber()==0){//first turn
			message="Turn,"+generateHeader()+"nextPlayer";
		}else{
			//put last turn result as we need to know who received the turn
			message=game.getTurnNumber()+","+generateFormat(lastId,lastScore)+agentID;
			try{
				Statistics.addPass(Integer.parseInt(lastId), Integer.parseInt(agentID));
			}catch (Exception e) {
				log.error("failed to parse index of agent for the passing table\n"+e);
			}
		}
		lastId=agentID;
		lastScore=score;
		if(game.getTurnNumber()+1==game.getNumberOfTurns()){
			message+="\n"+getLastMassage();
		}
		log.debug("message created: "+message);
		
		return  message; 
	}

	public void setContent(String agentID, String score) {
		setAgentID(agentID);
		setScore(score);
	}
	
	/**
	 * created the format String of 0,0,x,0,0
	 * @param id agent id
	 * @param score his score
	 * @return agent score in correct place in format (x) and 0 for all other
	 */
	private String generateFormat(String id,String score){
		String str="";
		for(int i=0;i<game.getAgents().size();i++){
			if((i+1)==Integer.parseInt(id)){
				str+=score+",";
			}else{
				str+="0,";
			}
		}
		return str;
	}
	/**
	 * header massage used in the csv table
	 * @return
	 */
	private String generateHeader(){
		String str="";
		for(int i=0;i<game.getAgents().size();i++){
			str+="player"+game.getAgents().get(i).getID()+",";
		}
		return str;
	}
	
	private String getLastMassage(){
		String str=(game.getTurnNumber()+1)+","+generateFormat(lastId,lastScore)+"X";
		return str;
	}

}
